# import time
# import asyncio
#
# from playwright.async_api import async_playwright
#
#
# # async def consumer(user, pwd):
# #     async with async_playwright() as p:
# #         browser = await p.chromium.launch(headless=False, args=["--start-maximized"])
# #         async with browser.new_context(no_viewport=True) as context:
# #             async with context.new_page() as page:
# #                 await page.goto("https://fe-bigevent-web.itheima.net/login")
# #                 await page.get_by_role("textbox", name="请输入用户名").fill(user)
# #                 await page.get_by_role("textbox", name="请输入密码").fill(pwd)
# #                 await page.get_by_role("button", name="登录").click()
# #                 await page.pause()  # 异步暂停，等待调试操作
# async def consumer(username, password):
#     async with async_playwright() as p:
#         browser = await p.chromium.launch(headless=False, args=["--start-maximized"])
#         async with browser.new_context(no_viewport=True) as context:
#             async with context.new_page() as page:
#                 await page.goto("https://fe-bigevent-web.itheima.net/login")
#                 await page.get_by_role("textbox", name="请输入用户名").fill(username)
#                 await page.get_by_role("textbox", name="请输入密码").fill(password)
#                 await page.get_by_role("button", name="登录").click()
#                 # 等待登录完成，可根据实际情况调整选择器
#                 # await page.wait_for_selector('.success-message', timeout=5000)
#                 # print(f"登录成功: {username}")
#
#
# async def main():
#     # 模拟 5 次相同用户的登录
#     credentials = {'username': 'iloveheima', 'password': 'admin1'}
#     tasks = [consumer(credentials['username'], credentials['password']) for _ in range(5)]
#
#     print(f"准备执行 {len(tasks)} 次登录")
#     await asyncio.gather(*tasks)
#
# if __name__ == '__main__':
#     s = time.perf_counter()
#     asyncio.run(main())
#     elapsed = time.perf_counter() - s
#     print(f"Finished in {elapsed:.2f} seconds.")


# import time
# import asyncio
#
# from playwright.async_api import async_playwright
#
#
# async def consumer(username, password):
#     async with async_playwright() as p:
#         browser = await p.chromium.launch(headless=False, args=["--start-maximized"])
#         async with browser.new_context(no_viewport=True) as context:
#             async with context.new_page() as page:
#                 await page.goto("https://fe-bigevent-web.itheima.net/login")
#                 await page.get_by_role("textbox", name="请输入用户名").fill(username)
#                 await page.get_by_role("textbox", name="请输入密码").fill(password)
#                 await page.get_by_role("button", name="登录").click()
#                 # 等待登录完成，可根据实际情况调整选择器
#                 await page.wait_for_selector('.success-message', timeout=5000)
#                 print(f"登录成功: {username}")
#
#
# async def main():
#     # 模拟 5 次相同用户的登录
#     credentials = {'username': 'iloveheima', 'password': 'admin1'}
#     tasks = [consumer(credentials['username'], credentials['password']) for _ in range(5)]
#
#     print(f"准备执行 {len(tasks)} 次登录")
#     print(tasks)
#     await asyncio.gather(*tasks)
#
#
# if __name__ == '__main__':
#     s = time.perf_counter()
#     asyncio.run(main())
#     elapsed = time.perf_counter() - s
#     # print(f"完成 {len(tasks)} 次登录，耗时: {elapsed:.2f} 秒")


import time
import asyncio
from playwright.async_api import async_playwright

# 存储 5 个不同用户的凭证
USERS = [
    {"username": "user1", "password": "pass1"},
    {"username": "user2", "password": "pass2"},
    {"username": "user3", "password": "pass3"},
    {"username": "user4", "password": "pass4"},
    {"username": "user5", "password": "pass5"},
]


async def consumer(user):
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=False, args=["--start-maximized"])
        async with browser.new_context(no_viewport=True) as context:
            async with context.new_page() as page:
                await page.goto("https://fe-bigevent-web.itheima.net/login")
                await page.get_by_role("textbox", name="请输入用户名").fill(user["username"])
                await page.get_by_role("textbox", name="请输入密码").fill(user["password"])
                await page.get_by_role("button", name="登录").click()

                # 等待登录成功的元素出现（根据实际页面调整选择器）
                try:
                    await page.wait_for_selector(".success-element", timeout=3000)
                    print(f"用户 {user['username']} 登录成功")
                except Exception as e:
                    print(f"用户 {user['username']} 登录失败: {e}")


async def main():
    # 为每个用户创建登录任务
    tasks = [consumer(user) for user in USERS]

    # 使用 Semaphore 限制并发浏览器数量（避免资源耗尽）
    semaphore = asyncio.Semaphore(3)  # 最多同时运行 3 个浏览器

    async def bounded_consumer(user):
        async with semaphore:
            return await consumer(user)

    bounded_tasks = [bounded_consumer(user) for user in USERS]

    print(f"开始执行 {len(USERS)} 个用户的登录任务")
    await asyncio.gather(*bounded_tasks)


if __name__ == '__main__':
    s = time.perf_counter()
    asyncio.run(main())
    elapsed = time.perf_counter() - s
    print(f"完成所有登录任务，耗时: {elapsed:.2f} 秒")